package com.example.securitydemo1.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 * ClassName: SecurityWeb
 * Package: com.example.securitydemo1.config
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-05-29
 * Time: 13:23
 */
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
//开启Security注解使用的注解
public class SecurityWeb extends WebSecurityConfigurerAdapter {
    @Resource
    private UserDetailsService userDetailsService;

    //自定义用户名密码
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }
    @Bean
    PasswordEncoder password(){
        return new BCryptPasswordEncoder();
    }


    //自定义登录页面
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //用户退出的配置       退出的路径   退出之后跳转到那个
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/add").permitAll();

        //配置403跳转
        http.exceptionHandling().accessDeniedPage("/hello.html");

        http.formLogin() //自定义自己的登录页面
            .loginPage("/login.html") //跳转到自定义的登录页面的地址
            .loginProcessingUrl("/user/login")  //自定义Controller的路径
            .defaultSuccessUrl("/success.html").permitAll() //登录成功之后要跳转的路径
            .and().authorizeRequests()  //哪些路由需要验证 哪些不需要验证
                .antMatchers("/","/test/add","/user/login").permitAll()  //这些路径就是直接可以访问 不需要认证

                //1.表示当前登录的用户 只用具有admin权限才可以访问这个路径 单个角色访问
                //.antMatchers("/test/index").hasAuthority("admins")  //添加权限访问

                //2.权限当中有其中某一个就可以访问
                //.antMatchers("/test/index").hasAnyAuthority("admins","manager")

                //3.角色的名称 ROLE_sale
                .antMatchers("/test/index").hasRole("sale")

            .anyRequest().authenticated() //所有请求都可以访问
            .and().csrf().disable();  //关闭csrf防护
    }
}
